package com.chezai.client.update;

import com.chezai.client.bean.DownloadProgress;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.xutils.common.Callback;

import java.io.File;

/**
 * Created by wyouflf on 15/11/10.
 */
/*package*/ class DownloadCallback implements Callback.CommonCallback<File>,
        Callback.ProgressCallback<File>, Callback.Cancelable {

    private final AppUpdateManager instance;
    private String TAG = this.getClass().getSimpleName();
    private boolean cancelled = false;
    private Cancelable cancelable;

    public DownloadCallback() {
        instance = AppUpdateManager.getInstance();
    }


    public void setCancelable(Cancelable cancelable) {
        this.cancelable = cancelable;
    }


    @Override
    public void onWaiting() {
        Logger.t(TAG).d("等待下载中");
    }

    @Override
    public void onStarted() {
        EventBus.getDefault().postSticky(new DownloadProgress(0, 0, DownloadProgress.STATE_START));
    }

    @Override
    public void onLoading(long total, long current, boolean isDownloading) {
        EventBus.getDefault().postSticky(new DownloadProgress(total, current, DownloadProgress.STATE_LOADING));
    }

    @Override
    public void onSuccess(File result) {
        instance.setUpdating(false);
        DownloadProgress progress = new DownloadProgress(0, 0, DownloadProgress.STATE_SUCESS);
        progress.filePath = result.getAbsolutePath();
        EventBus.getDefault().postSticky(progress);
    }

    @Override
    public void onError(Throwable ex, boolean isOnCallback) {
        instance.setUpdating(false);
        EventBus.getDefault().postSticky(new DownloadProgress(0, 0, DownloadProgress.STATE_FAILE));
    }

    @Override
    public void onCancelled(CancelledException cex) {
        instance.setUpdating(false);
    }

    @Override
    public void onFinished() {
        instance.setUpdating(false);
        cancelled = false;
        EventBus.getDefault().post(new DownloadProgress(0, 0, DownloadProgress.STATE_FINISH));
    }


    @Override
    public void cancel() {
        cancelled = true;
        if (cancelable != null) {
            cancelable.cancel();
        }
    }

    @Override
    public boolean isCancelled() {
        return cancelled;
    }
}
